package com.doubao.hardware.service;

import com.doubao.hardware.config.IotMqConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * MQTT服务
 * 用于发送消息到MQTT代理
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MqttService {

    private final IotMqConfig iotMqConfig;
    private final ObjectMapper objectMapper;

    /**
     * 发送字符串消息
     *
     * @param payload 消息内容
     * @return 是否发送成功
     */
    public boolean sendMessage(String payload) {
        try {
            iotMqConfig.publish(payload);
            return true;
        } catch (Exception e) {
            log.error("发送MQTT消息失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送对象消息，自动转换为JSON
     *
     * @param data 消息对象
     * @return 是否发送成功
     */
    public boolean sendMessage(Object data) {
        try {
            String payload = objectMapper.writeValueAsString(data);
            return sendMessage(payload);
        } catch (JsonProcessingException e) {
            log.error("序列化消息对象失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送消息到指定主题
     *
     * @param topic 主题
     * @param payload 消息内容
     * @return 是否发送成功
     */
    public boolean sendMessageToTopic(String topic, String payload) {
        try {
            if (!iotMqConfig.isConnected()) {
                iotMqConfig.getMqtt();
            }

            if (iotMqConfig.isConnected()) {
                iotMqConfig.getIotMqttClient().publish(topic, payload.getBytes(), 1, false);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("发送MQTT消息到指定主题失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送对象消息到指定主题，自动转换为JSON
     *
     * @param topic 主题
     * @param data 消息对象
     * @return 是否发送成功
     */
    public boolean sendMessageToTopic(String topic, Object data) {
        try {
            String payload = objectMapper.writeValueAsString(data);
            return sendMessageToTopic(topic, payload);
        } catch (JsonProcessingException e) {
            log.error("序列化消息对象失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 检查MQTT连接状态
     *
     * @return 连接状态
     */
    public boolean isConnected() {
        return iotMqConfig.isConnected();
    }

    /**
     * 重新建立MQTT连接
     *
     * @return 是否连接成功
     */
    public boolean reconnect() {
        try {
            iotMqConfig.getMqtt();
            return iotMqConfig.isConnected();
        } catch (Exception e) {
            log.error("重新连接MQTT失败: {}", e.getMessage(), e);
            return false;
        }
    }
}